package com.woniu.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @author xiaoqi
 * @time 2021/01/03 17:38:57
 */
//RootConfig只管业务层和dao层，顶替了spring-config.xml
@EnableTransactionManagement    //事务管理的注解
@Configuration//核心配置
@ComponentScan("com.woniu.service")  //扫包
public class RootConfig {

    @Bean
    public DataSource ds(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql:///test");
        ds.setUsername("root");
        ds.setPassword("root");
        return ds;
    }

    //有参代表自动装配
    @Bean
    public SqlSessionFactoryBean ssf(DataSource ds){
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        ssfb.setDataSource(ds);
        //添加别名
        ssfb.setTypeAliasesPackage("com.woniu.entity");
        return ssfb;
    }

    @Bean
    public MapperScannerConfigurer mapperScanner(){
        MapperScannerConfigurer ms = new MapperScannerConfigurer();
        ms.setBasePackage("com.woniu.mapper");
        return ms;
    }
    //事务管理
    //写法一：自动装配
    @Bean
    public DataSourceTransactionManager transactionManager(DataSource ds){
        DataSourceTransactionManager tm = new DataSourceTransactionManager();
        tm.setDataSource(ds);
        return tm;
    }

//    //写法二：非自动装配，调方法
//    @Bean
//    public DataSourceTransactionManager transactionManager(){
//        DataSourceTransactionManager tm = new DataSourceTransactionManager();
//        //调数据源方法
//        tm.setDataSource(ds());
//        return tm;
//    }

}
